﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.IO;
using System.Xml.Linq;
using AppEntity;

namespace AppEntity
{
    public class Base
    {

        /// <summary>
        /// 获取备份文件夹路径
        /// </summary>
        /// <returns></returns>
        public static string GetBackupPath()
        {
            return GlobalCache.GetGlobalConfig().SelectSingleNode("/root/backup").InnerText;
        }
        /// <summary>
        /// 获取所有App的列表
        /// </summary>
        /// <returns></returns>
        public static XDocument GetAppIndex()
        {
            return XDocument.Load(GetSettingsPath() + "index.xml");
        }

        /// <summary>
        /// 获取 AppEntityDataBase 文件夹位置。如：d:\AppEntity\AppEntityDataBase\。
        /// </summary>
        /// <returns></returns>
        public static string GetDataBasePath()
        {
            return GlobalCache.GetGlobalConfig().SelectSingleNode("/root/database").InnerText;
        }

        /// <summary>
        /// 构造指定 App 的数据库文件路径
        /// </summary>
        /// <param name="AppID"></param>
        /// <returns></returns>
        public static string GetDataBaseFilePath(string AppID)
        {            
            return GetDataBasePath() + AppID + ".sqlite";
        }

        /// <summary>
        /// 获取 AppEntitySettings 文件夹位置。如：d:\AppEntity\AppEntitySettings。
        /// </summary>
        /// <returns></returns>
        public static string GetSettingsPath()
        {
            return GlobalCache.GetGlobalConfig().SelectSingleNode("/root/settings").InnerText;
        }

        /// <summary>
        /// 获取指定 App 的 appsetting.xml 文件路径。如：d:\AppEntity\AppEntitySettings\100120\appsetting.xml
        /// </summary>
        /// <param name="AppID"></param>
        /// <returns></returns>
        public static string GetSettingsPath(string AppID)
        {
            return GetSettingsPath() + AppID + "\\appsetting.xml";
        }

        /// <summary>
        /// 获取指定 Entity 的 entity123456.xml 文件路径，如：d:\AppEntity\AppEntitySettings\100120\entity123456.xml
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="EntityID"></param>
        /// <returns></returns>
        public static string GetSettingsPath(string AppID, string EntityID)
        {
            return GetSettingsPath()+ AppID + "\\entity"+EntityID+".xml";
        }
       
        /// <summary>
        /// 从缓存中获取指定 App 的配置文件，如果缓存中不存在此配置，则初始化。
        /// </summary>
        /// <param name="AppID"></param>
        /// <returns></returns>
        public static XmlDocument GetAppSetting(string AppID)
        {
            string SettingFile = GetSettingsPath(AppID);
            return GetSettingFile(SettingFile);
        }

        /// <summary>
        /// 从缓存中获取指定 Entity 的配置文件，如果缓存中不存在此配置，则初始化。
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="EntityID"></param>
        /// <returns></returns>
        public static XmlDocument GetEntitySetting(string AppID, string EntityID)
        { 
            string SettingFile = GetSettingsPath(AppID, EntityID);
            return GetSettingFile(SettingFile);
        }

        private static XmlDocument GetSettingFile(string SettingFile)
        {
            if (HttpRuntime.Cache[SettingFile] != null)
            {
                return (XmlDocument)HttpRuntime.Cache[SettingFile];
            }
            XmlDocument dom = new XmlDocument();
            dom.LoadFile(SettingFile);
            System.Web.Caching.CacheDependency Dep = new System.Web.Caching.CacheDependency(SettingFile);
            HttpRuntime.Cache.Add(SettingFile, dom, Dep, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), System.Web.Caching.CacheItemPriority.AboveNormal, null);
            return dom;
        }

        /// <summary>
        /// 返回 当前 theme 的位置，如：D:\AppEntityInSqlite\AppEntityWebSite\theme\theme01\
        /// </summary>
        /// <returns></returns>
        public static string GetThemeFolder()
        {
            string Theme = "01";
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Request.Cookies["theme"] == null)
                {
                    HttpContext.Current.Response.Cookies["theme"].Value = Theme;
                    HttpContext.Current.Response.Cookies["theme"].Expires = DateTime.Now.AddMonths(1);
                }
                else
                {
                    Theme = HttpContext.Current.Request.Cookies["theme"].Value;
                }
            }
            return AppEntity.GlobalCache.GetGlobalConfig().SelectSingleNode("/root/website").InnerText+"theme\\theme"+Theme+"\\";
        }
        /// <summary>
        /// 返回 当前 theme 的位置，如：D:\AppEntityInSqlite\AppEntityWebSite\theme\theme01\xsl\
        /// </summary>
        /// <returns></returns>
        public static string GetThemeXslFolder()
        {
            return GetThemeFolder() + "xsl\\";
        }

        public static string[] GetMaxID(int n)
        {
            return GetMaxID(Base.GetSettingsPath()+"MAXID",n);
        }
        public static string[] GetMaxID(string maxidfile, int n)
        {
            string id = "1000000"; //百万
            if (File.Exists(maxidfile))
            {
                FileStream Fs = new FileStream(maxidfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(Fs, Encoding.UTF8);
                string mid = reader.ReadLine();
                reader.Close();
                Fs.Close();
                if (!string.IsNullOrEmpty(mid))
                {
                    id = mid;
                }
            }
            int idvalue = System.Convert.ToInt32(id);

            string[] idarr = new string[n];
            int counter = 0;
            for (int i = idvalue + 1; i <= idvalue + n; i++)
            {
                idarr[counter] = i.ToString();
                counter++;
            }
            FileStream Fs2 = new FileStream(maxidfile, FileMode.Create, FileAccess.Write, FileShare.Read);
            StreamWriter writer = new StreamWriter(Fs2, Encoding.UTF8);
            writer.Write(idvalue + n);
            writer.Close();
            Fs2.Close();
            return idarr;
        }
    }

}
